package com.luceneheritrixbook.database;

import java.sql.*;

import com.luceneheritrixbook.core.Product;

public class ProductJDBC {

	private Connection con = null;

	private Statement stmt = null;

	private ResultSet rs = null;

	private PreparedStatement pstmt = null;

	private boolean autoCommit = true;

	public ProductJDBC(String url, String usr, String pwd) throws Exception {
		Class.forName("com.mysql.jdbc.Driver").newInstance();
		con = DriverManager.getConnection(url, usr, pwd);
		con.setAutoCommit(autoCommit);
	}

	public int addProduct(Product p) throws Exception {

		int nextid = getNextId();

		if (nextid < 0) {
			throw new Exception("Can't get next id.");
		}

		// since we get the next id, add the info to db
		String content = p.getContent();
		String summary = p.getSummary();
		String imageURI = p.getImageURI();
		String originalUrl = p.getOriginalUrl();
		String category = p.getCategory();
		String name = p.getName();
		String type = p.getType();
		String updatedtime = p.getUpdatedtime();

		String expr = "insert into product (content, abstractcontent, url, imageurl, category, name, type, updatedtime) values(?,?,?,?,?,?,?,?)";
		pstmt = con.prepareStatement(expr);

		System.out.println("======================="+content);

		pstmt.setString(1, content);
		pstmt.setString(2, summary);
		pstmt.setString(3, originalUrl);
		pstmt.setString(4, imageURI);
		pstmt.setString(5, category);
		pstmt.setString(6, name);
		pstmt.setString(7, type);
		pstmt.setString(8, updatedtime);

/*		String expr = "insert into product (content, abstractcontent, url, imageurl, category, name, type, updatedtime) values("
			+ content +","+ summary+","+originalUrl+","+imageURI+","+category+","+name+","+type+","+updatedtime+")";
		
		pstmt = con.prepareStatement(expr);
				*/
		pstmt.execute();

		return nextid;
	}

	private int getNextId() throws Exception {

		int result = -1;

		String sql = "select max(id)+1 from product";

		stmt = con.createStatement();
		rs = stmt.executeQuery(sql);

		while (rs.next()) {
			result = rs.getInt(1);
		}

		return result;
	}

	public void close() {
		if (con != null) {
			try {
				con.close();
			} catch (Exception e) {
				e.printStackTrace();
			} finally {
				con = null;
			}
		}
	}

	public static void main(String[] args) {
		String url = "jdbc:mysql://localhost/mobiledb";
		String usr = "root";
		String pwd = "admin";
		try {
			new ProductJDBC(url, usr, pwd);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
		}
	}

}
